package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"fmt"

	log "github.com/sirupsen/logrus"
)

func GetPaidPropsPacksConfig(paidId int64) (config data.PaidPropsPack, err error) {
	// 读表
	tpl, ok := data.Get("PaidPropsPacks", uint64(paidId))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有找到PaidPropsPacks付费包，tid:%d", paidId))
		return
	}
	config = tpl.(data.PaidPropsPack)
	return config, err
}

// 获取活动礼包
func GetActPack(u *m.User) (ap *m.ActPack, err error) {
	ap = u.GetActPack()
	defer ap.Update(ap)

	now := utils.TNow().Unix()
	tplLst, ok := data.Filters("ActPaidProps", func(val interface{}) bool {
		valT := val.(data.ActPaidProp)
		bTime, _ := utils.LayoutToTime(valT.BeginTime)
		eTime, _ := utils.LayoutToTime(valT.EndTime)
		if bTime.Unix() <= now && now <= eTime.Unix() {
			return true
		}
		return false
	})
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表ActPaidProps")
		return
	}
	// 把玩家身上的活动礼包，不在时间范围内的活动删掉
	lst := make([]int64, 0) // 记录要删掉的活动
	for key, val := range ap.MGiftPack {
		if val.EndTime < now { // 现在时间大于活动礼包结束时间，记录
			lst = append(lst, key)
		}
	}
	// 删掉玩家身上超时的活动
	for _, item := range lst {
		delete(ap.MGiftPack, item)
	}
	// 将玩家没有的活动，添加到玩家身上
	for _, item := range tplLst {
		itemT := item.(data.ActPaidProp)
		if _, ok := ap.MGiftPack[int64(itemT.Id)]; !ok {
			tid := int64(itemT.Id)
			bTime, _ := utils.LayoutToTime(itemT.BeginTime)
			eTime, _ := utils.LayoutToTime(itemT.EndTime)
			gp := &m.GiftPack{
				Tid:       tid,
				PackIdLst: make([]int64, 0),
				BeginTime: bTime.Unix(),
				EndTime:   eTime.Unix(),
				BuyCnt:    0,
				PackTyp:   int64(itemT.PackTyp),
			}
			for _, item1 := range itemT.PackIdLst {
				gp.PackIdLst = append(gp.PackIdLst, int64(item1))
			}
			ap.MGiftPack[tid] = gp
		}
	}
	return
}

func GetActPackId(u *m.User, tid int64) (gp *m.GiftPack, err error) {
	ap := u.GetActPack()
	defer ap.Update(ap)

	gp, ok := ap.MGiftPack[tid]
	if !ok {
		err = errors.NewErrcode(data.Errcode.NotFound, "没有找到该礼包信息")
		return
	}
	return
}

// 购买活动礼包
func BuyActPack(from string, u *m.User, tid int64, UnionSendRedPacketReq func(packId int64), PSend func(interface{}) error) (buyingPackId int64, ap *m.ActPack, uProp *m.UpdateProp, resGoods []*m.Goods, boxResList []*m.BoxRes, err error) {
	ap = u.GetActPack()
	defer ap.Update(ap)

	gp, ok := ap.MGiftPack[tid]
	if !ok {
		err = errors.NewErrcode(data.Errcode.NotFound, "没有找到该礼包信息")
		return
	}

	if int64(len(gp.PackIdLst)) <= gp.BuyCnt {
		err = errors.NewErrcode(data.Errcode.ServerErr, "购买次数大于礼包长度")
		return
	}

	packId := gp.PackIdLst[gp.BuyCnt]
	tpl, ok := data.Get("PaidPropsPacks", uint64(packId))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表PaidPropsPacks")
		return
	}
	tplT := tpl.(data.PaidPropsPack)
	// 免费礼包并且不是免费协议
	if int64(tplT.Typ) == data.PaidPropsEnum.FreePack && from != "ActPackBuyRequest" {
		err = errors.NewErrcode(data.Errcode.ServerErr, "免费礼包没有走免费协议")
		log.WithFields(log.Fields{
			"packId": packId,
			"from":   from,
			"method": "BuyActPack",
		}).Error("免费礼包没有走免费协议")
		return
	}

	// 打包道具
	giveGoods := make([]m.BaseKV, 0)
	for _, item := range tplT.Goods {
		gtpl, ok := data.Get("Goods", item.Key)
		if !ok {
			err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表Goods")
			return
		}
		gtplT := gtpl.(data.Good)
		if int64(gtplT.Category) == data.GoodsCategoryEnum.CategoryLv3 { // 宝箱，需要一个一个给
			for i := int64(0); i < int64(item.Value); i++ {
				giveGoods = append(giveGoods, m.BaseKV{Key: int64(item.Key), Val: 1})
			}
		} else {
			giveGoods = append(giveGoods, m.BaseKV{Key: int64(item.Key), Val: int64(item.Value)})
		}
	}
	// 给用户道具
	uProp, resGoods, boxResList, err = GiveGoodsByKvList(from, u, giveGoods, PSend)
	if err != nil {
		return
	}
	gp.BuyCnt++
	buyingPackId = packId
	// 购买的礼包是分享礼包，需要公会
	if gp.PackTyp == data.PaidPropsEnum.ShareBagPack {
		UnionSendRedPacketReq(packId)
	}
	return
}

// 重置活动礼包
func ResetActPack(u *m.User) {
	ap := u.GetActPack()
	ap.MGiftPack = make(map[int64]*m.GiftPack)
	ap.Update(ap)
}

// 购买免费礼包
func BuyFreePack(u *m.User, tid int64, from string, PSend func(interface{}) error) (uProp *m.UpdateProp, resGoods []*m.Goods, boxResList []*m.BoxRes, err error) {
	packId := tid
	tpl, ok := data.Get("PaidPropsPacks", uint64(packId))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, fmt.Sprintf("没有找到该配置表PaidPropsPacks，tid:%d", packId))
		return
	}
	tplT := tpl.(data.PaidPropsPack)
	if int64(tplT.Typ) != data.PaidPropsEnum.FreePack {
		err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("付费包不为免费包，不能直接购买，tid:%d", packId))
		return
	}
	// 打包道具
	giveGoods := make([]m.BaseKV, 0)
	for _, item := range tplT.Goods {
		gtpl, ok := data.Get("Goods", item.Key)
		if !ok {
			err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表Goods")
			return
		}
		gtplT := gtpl.(data.Good)
		if int64(gtplT.Category) == data.GoodsCategoryEnum.CategoryLv3 { // 宝箱，需要一个一个给
			for i := int64(0); i < int64(item.Value); i++ {
				giveGoods = append(giveGoods, m.BaseKV{Key: int64(item.Key), Val: 1})
			}
		} else {
			giveGoods = append(giveGoods, m.BaseKV{Key: int64(item.Key), Val: int64(item.Value)})
		}
	}
	// 给用户道具
	uProp, resGoods, boxResList, err = GiveGoodsByKvList(from, u, giveGoods, PSend)
	if err != nil {
		return
	}
	return
}
